<?php

namespace app\api\controller;

use app\api\biz\MenuBiz;
use app\api\biz\UserBiz;
use app\common\Cache;
use app\common\controller\ApiController;
use app\common\Result;
use joncc\attribute\attr\AuthNeedless;
use joncc\attribute\attr\Comment;
use joncc\attribute\attr\Params;
use joncc\attribute\attr\PermissionDefine;
use joncc\attribute\attr\PermissionNeedless;
use think\response\Json;

#[Comment('登录')]
#[AuthNeedless('login')]
#[PermissionNeedless('logout,userInfo')]
#[PermissionDefine('login', '登录')]
#[PermissionDefine('logout', '登出')]
#[PermissionDefine('userInfo', '用户信息')]
class Login extends ApiController
{

    #[Params('account', Params::STRING, true, "账号")]
    #[Params('password', Params::STRING, true, "密码")]
    public function login(): Json
    {
        $userBiz = UserBiz::login(p('account'), p('password'));
        if ($userBiz::hasError()) {
            return Result::fail(...$userBiz::getError());
        }
        return Result::success($userBiz::getData());
    }

    public function logout(): Json
    {
        $userBiz = UserBiz::logout();
        if ($userBiz::hasError()) {
            return Result::fail(...$userBiz::getError());
        }

        return Result::success($userBiz::getData());
    }

    public function userInfo(): Json
    {
        $menuBiz = MenuBiz::userList();
        if ($menuBiz::hasError()) {
            return Result::fail(...$menuBiz::getError());
        }
        $info = $menuBiz::getData();
        if (empty($info)) {
            return Result::fail('无菜单权限，请联系管理员！');
        }

        $uid = Cache::get(\app\common\enum\Cache::UID);
        $userBiz = UserBiz::detail($uid);
        if ($userBiz::hasError()) {
            return Result::fail(...$userBiz::getError());
        }
        $user = $userBiz::getData();
        $data = [
            'perms' => $info['perms'],
            'menu' => $info['menu'],
            'user' => $user,
        ];

        return Result::success($data);
    }
}